#include "stdafx.h"

#include "CGSMAudioDecoder.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


CGSMAudioDecoder::~CGSMAudioDecoder()
{
	gsm_destroy(m_handle);
	if(m_resampler)
	{
		delete m_resampler;
	}

	if(m_stream)
	{
		delete m_stream;
	}
}

CGSMAudioDecoder::CGSMAudioDecoder():
	m_resampler(0),
	m_stream_len(320),
	m_stream(0),
	m_bUseResampler(false)
{
	m_handle = gsm_create();
	m_stream = new BYTE [320];
	::memset(m_stream, 0, 320);
}

const WAVEFORMATEX&  CGSMAudioDecoder::Format() const
{
	return (m_required);
}

DWORD CGSMAudioDecoder::Decode(BYTE *from, BYTE *to)
{
	if(m_bUseResampler)
	{
		gsm_decode(m_handle,from,reinterpret_cast<short*>(m_stream));
		long lSamples = 0;
		m_resampler->Resample(m_stream, to, 160, &lSamples);
		return lSamples*2;
	} else
	{
		gsm_decode(m_handle,from,reinterpret_cast<short*>(to));
		return 320;
	}
}

bool CGSMAudioDecoder::Open(const WAVEFORMATEX & required_format)
{
	m_required = required_format;
	::memset(&m_format, 0, sizeof(WAVEFORMATEX));
	m_format.wFormatTag = WAVE_FORMAT_PCM;
	m_format.nChannels  = 1;
	m_format.wBitsPerSample = 16;// 16-bits per mono sample
	m_format.nSamplesPerSec = 8000;
	m_format.nBlockAlign = 4;
	m_format.nAvgBytesPerSec = 2*1*8000;
	m_format.cbSize=sizeof(WAVEFORMATEX);

	if( IsNeedResampler())
	{

		// create resampler
		m_resampler  = new CAudioResampler(&m_format, 320, m_required.nSamplesPerSec, false, false);
		if(!m_resampler)
		{
			return false;
		}

		long len = m_resampler->StreamLen();
		if(len != 320)
		{
			m_stream_len = len;
		}

		m_bUseResampler = true;
	}

	return true;
}

bool CGSMAudioDecoder::IsNeedResampler()
{

	if(m_format.nChannels != m_required.nChannels)
	{
		return true;
	}

	return false;
}